package Tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    Socket socket = null;
    public TcpEchoClient(String serverIP, int serverPort) throws IOException {
        //连接是服务器进行建立的，客户端不需要管，只需要通过socket来传递就行
        socket = new Socket(serverIP,serverPort);
    }

    private void start() {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream)) {
            while(true) {
                System.out.print("->");
                //1.从控制台读取一个请求,这里使用next方法，next的特点是遇到空白符就结束读取
                String request = scanner.next();
                //2.向服务器发送请求
                writer.println(request);
                writer.flush();
                //3.读取响应
                String response = scannerNetwork.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
